unit scTreeHandler;

interface

uses
  ComCtrls, ZDataset, SysUtils;

const
  TREE_SQL = 'SELECT c.*, h.parent_id FROM code c JOIN code_href h ON (c.id = code_id) WHERE parent_id = :parent_id ORDER by c.codeorder, c.id';

type
  TNodeData = class
     id : Integer;
     code : string;
     order : Integer;
     shortName : string;
     name : string;
  end;

  procedure fillTree(root: TTreeNode; id: Integer; tv : TTreeView);
  function getNodeById(id: Integer; tv : TTreeView): TTreeNode;

implementation

uses scDmDao;

procedure fillTree(root: TTreeNode; id: Integer; tv : TTreeView);
var
 node : TTreeNode;
 q : TZQuery;
 nodeText : string;
begin
  q := TZQuery.Create(nil);
  try
     q.Connection := dmDao.conSms;
     q.SQL.Add(TREE_SQL);
     q.ParamByName('parent_id').asInteger := id;
     q.Open;
     while not q.Eof do
     begin
       nodeText := q.FieldByName('code').AsString + #32 + q.FieldByName('shortname').AsString;
       node := tv.Items.AddChild(root, nodeText);
       if Assigned(node.Data) then TNodeData(node.Data).Free;
       node.Data := TNodeData.Create;
       TNodeData(node.Data).id := q.FieldByName('id').AsInteger;
       TNodeData(node.Data).code := q.FieldByName('code').AsString;
       TNodeData(node.Data).order := q.FieldByName('codeorder').AsInteger;
       TNodeData(node.Data).name := q.FieldByName('name').AsString;
       TNodeData(node.Data).shortName := q.FieldByName('shortname').AsString;
       fillTree(node,q.FieldByName('id').AsInteger,tv);
       q.Next;
     end;
  finally
     q.Close;
     FreeAndNil(q);
  end;
end;

function getNodeById(id: Integer; tv : TTreeView): TTreeNode;
var
  node: TTreeNode;
begin
   Result := nil;
   node := tv.Items.GetFirstNode;
   while node <> nil do
   begin
     if Assigned(node.Data) and (TNodeData(node.Data).id = id) then
     begin
       Result := node;
       Break;
     end;
     node := node.GetNext;
   end;

end;

end.
